package logger

import (
	"fmt"
	"os"
	
	"fiber-layout/provider/config"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var Log *zap.Logger

func InitLogger() {
	systemWriter := getWriter()
	
	if len(systemWriter) != 0 {
		Log = zap.New(
			zapcore.NewCore(getEncoder(), zapcore.NewMultiWriteSyncer(systemWriter...), zap.DebugLevel),
			zap.AddCaller(), zap.AddStacktrace(zap.DebugLevel),
		)
	} else {
		Log = zap.L()
	}
	fmt.Println("初始化日志成功")
}

//getEncoder 获取日志格式
func getEncoder() zapcore.Encoder {
	return zapcore.NewJSONEncoder(
		zapcore.EncoderConfig{
			MessageKey:       "msg", //相关键名
			LevelKey:         "level",
			TimeKey:          "time",
			NameKey:          "name",
			CallerKey:        "call",
			FunctionKey:      "func",
			StacktraceKey:    "stack",
			LineEnding:       zapcore.DefaultLineEnding,
			EncodeLevel:      zapcore.LowercaseColorLevelEncoder,
			EncodeTime:       zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000"),
			EncodeDuration:   zapcore.SecondsDurationEncoder,
			EncodeCaller:     zapcore.FullCallerEncoder,
			EncodeName:       zapcore.FullNameEncoder,
			ConsoleSeparator: "", //控制台分隔符
		},
	)
}

func getWriter() []zapcore.WriteSyncer {
	var logWriter []zapcore.WriteSyncer
	//如果是调试模式 打印在控制台
	if config.Config.GetBool("debug") {
		logWriter = append(logWriter, zapcore.Lock(os.Stdout))
	}
	
	Hook := lumberjack.Logger{
		MaxSize:    config.Config.GetInt("log.maxSize"),    // 每个日志文件保存的大小 单位:M
		MaxAge:     config.Config.GetInt("log.maxAge"),     // 文件最多保存多少天
		MaxBackups: config.Config.GetInt("log.maxBackups"), // 日志文件最多保存多少个备份
		Compress:   config.Config.GetBool("log.compress"),  // 是否压缩
	}
	
	//如果开启了写入系统日志
	if config.Config.GetBool("log.wireFile") {
		Hook.Filename = config.Config.GetString("log.path")
		logWriter = append(logWriter, zapcore.Lock(zapcore.AddSync(&Hook)))
	}
	return logWriter
}
